package com.aliang.shopping.config;

import cn.hutool.core.util.StrUtil;
import com.aliang.shopping.contact.SqlColumnConstant;
import com.aliang.shopping.esDao.GoodsEsRepository;
import com.aliang.shopping.mapper.GoodsMapper;
import com.aliang.shopping.mapper.GoodsSkuMapper;
import com.aliang.shopping.model.converter.GoodsConverter;
import com.aliang.shopping.model.dto.goods.GoodsEsDto;
import com.aliang.shopping.model.po.Goods;
import com.aliang.shopping.model.po.GoodsSku;
import com.aliang.shopping.service.OrdersInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.elasticsearch.BulkFailureException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@AllArgsConstructor
@Slf4j
class ESConfig {


    private final GoodsEsRepository goodsEsRepository;
    private final GoodsMapper goodsMapper;
    private final GoodsConverter goodsConverter;
    private final GoodsSkuMapper goodsSkuMapper;
    private final OssConfig ossConfig;
    private final OrdersInfoService ordersInfoService;

    /**
     * 初始化数据
     */
    @PostConstruct
    public void init() {
        //删除全部es数据
        goodsEsRepository.deleteAll();
        //查询全部合适的商品数据
        LambdaQueryWrapper<Goods> wrapper = new LambdaQueryWrapper<>();
        //售卖的商品
        wrapper.eq(Goods::getStatus, SqlColumnConstant.STATUS_OK);
        List<Goods> goodsList = goodsMapper.selectList(wrapper);
        if (goodsList.isEmpty()) return;
        //获取商品Id
        List<Long> goodsIds = goodsList.stream().map(Goods::getId).distinct().collect(Collectors.toList());
        //获取最低的价格数据
        List<GoodsSku> goodsSkus = this.goodsSkuMapper.selectListByGoodsId(goodsIds);
        //转换成map
        Map<Long, BigDecimal> collect = goodsSkus.stream().collect(Collectors.toMap(GoodsSku::getGoodsId, GoodsSku::getPrice));
        // 获取商品销售数据
        Map<Long, Integer> saleNumMap = this.ordersInfoService.getSaleNumByGoodsId(goodsIds);
        // 转换数据
        List<GoodsEsDto> esDtoList = goodsConverter.toEsDtoList(goodsList);

        //设置图片
        esDtoList.forEach(esDto -> {
            //设置价格
            esDto.setPrice(collect.get(esDto.getId()));
            // 如果商品主图不为空，设置完整路径
            if (StrUtil.isNotBlank(esDto.getMainImages())) {
                esDto.setMainImages(ossConfig.getUrl() + esDto.getMainImages());
            }
            // 设置销量
            esDto.setSaleNum(saleNumMap.getOrDefault(esDto.getId(), 0));
        });
        // 保存数据到es
        try {
            this.goodsEsRepository.saveAll(esDtoList);
        } catch (BulkFailureException e) {
            e.getFailedDocuments().forEach((id, failure) -> {
                log.error("Failed to save document with ID {}: {}", id, failure);
            });
            e.printStackTrace();
        }
    }
}
